package service

import (
	"time"

	// "GinAdmin/internal/model"
	// "GinAdmin/pkg/database"
	"GinAdmin/core/database"
	"GinAdmin/model"
)

// MessageService 消息服务
type MessageService struct{}

// CreateMessage 创建消息
func (s *MessageService) CreateMessage(req *model.CreateMessageRequest) (*model.Message, error) {
	message := model.Message{
		Title:   req.Title,
		Content: req.Content,
		Type:    req.Type,
		Status:  0, // 默认未读
		UserID:  req.UserID,
	}

	if err := database.DB.Create(&message).Error; err != nil {
		return nil, err
	}

	return &message, nil
}

// ReadMessage 读取消息
func (s *MessageService) ReadMessage(id, userID uint) error {
	var message model.Message
	if err := database.DB.Where("id = ? AND user_id = ?", id, userID).First(&message).Error; err != nil {
		return err
	}

	// 已读状态
	if message.Status == 1 {
		return nil
	}

	now := time.Now()
	updates := map[string]interface{}{
		"status":    1,
		"read_time": &now,
	}

	if err := database.DB.Model(&message).Updates(updates).Error; err != nil {
		return err
	}

	return nil
}

// DeleteMessage 删除消息
func (s *MessageService) DeleteMessage(id, userID uint) error {
	return database.DB.Where("id = ? AND user_id = ?", id, userID).Delete(&model.Message{}).Error
}

// GetUserMessages 获取用户消息
func (s *MessageService) GetUserMessages(userID uint, page, pageSize int, status int) ([]model.Message, int64, error) {
	var messages []model.Message
	var total int64

	db := database.DB.Model(&model.Message{}).Where("user_id = ?", userID)

	// 按状态筛选
	if status != -1 {
		db = db.Where("status = ?", status)
	}

	// 获取总数
	if err := db.Count(&total).Error; err != nil {
		return nil, 0, err
	}

	// 分页查询
	if err := db.Offset((page - 1) * pageSize).Limit(pageSize).
		Order("created_at DESC").
		Find(&messages).Error; err != nil {
		return nil, 0, err
	}

	return messages, total, nil
}

// GetUnreadCount 获取未读消息数量
func (s *MessageService) GetUnreadCount(userID uint) (int64, error) {
	var count int64
	if err := database.DB.Model(&model.Message{}).Where("user_id = ? AND status = 0", userID).Count(&count).Error; err != nil {
		return 0, err
	}
	return count, nil
}
